package com.totoro.controller;

import com.totoro.pojo.Product;
import com.totoro.pojo.User;
import com.totoro.pojo.UserOnline;
import com.totoro.service.CartService;
import com.totoro.service.UserService;
import com.totoro.service.impl.UserServiceImpl;
import com.totoro.utils.Base64EncryptionUtil;
import com.totoro.utils.MailUtil;
import com.totoro.utils.ToolSecurityPwd;
import com.totoro.utils.TotoroUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author TOTORO
 * @date 2021/5/10 14:39
 * 登录业务处理控制器
 */
@Controller
@RequestMapping("/login")
public class LoginFormController {
    private static String beforePhone = "";
    private static String beforeCode = "";
    /** 密码验证方式 */
    private static final String EMAIL = "email";
    private static final String PHONE = "phone";
    final Timer timer=new Timer();

    @Autowired
    private UserService usi;
    @Autowired
    CartService cartService;


    /**
     * 登录验证
     * @param request
     * @return
     */
    @RequestMapping(value = "/login_check", method = RequestMethod.POST)
    public String loginCheck(HttpServletRequest request){
        String encodingUrl = request.getParameter("url");
        String requestUrl = "/";
        // 判断url是否拥有
            try {
                byte convert[] = encodingUrl.getBytes("UTF-8");
                if(encodingUrl.length() > 0) {
                    requestUrl = new String(Base64EncryptionUtil.base64Decrypt(convert));
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        String type = request.getParameter("type");
        // 获取到登录方式，手机号或者用户名邮箱
        // 指定以下两种登录方式
        String userLogin = "user", phoneLogin = "phone";
        if(userLogin.equals(type)){
            String value = request.getParameter("user");
            String password = request.getParameter("password");
            // 根据用户名查询是否有该用户
            User user = usi.checkUser(value);
            boolean ish = null!=user;
            // 如果有该用户
            if(ish){
                // 判断是否已被封禁
                if(user.getIsDelete() == 1){
                    return "redirect:/login.htm?error=c2&ttr="+encodingUrl;
                }
                // 获取该用户的密码盐，进行加密比较
                String salt = user.getSalt();
                String encryptPassword = user.getPassword();
                boolean isScd = ToolSecurityPwd.authenticate(password, encryptPassword, salt);
                // 如果密码比较正确
                if(isScd){
                    HttpSession userSession = request.getSession();
                    userSession.setMaxInactiveInterval(60*30);
                    userSession.setAttribute("user",user);
                    // 获取购物车商品，存进session
                    List<Product> productList = cartService.findCartProduct(user.getUserId());
                    if(productList.size()>5){
                        userSession.setAttribute("carts", productList.subList(0, 5));
                    } else {
                        userSession.setAttribute("carts", productList);
                    }
                    // 增加今日用户数
                    String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                    UserOnline userOnline = usi.findDayUserOnline(new UserOnline(0,user.getUserId(),0,nowDate, nowDate));
                    if(null == userOnline) {
                        usi.addUserOnlineCount(user.getUserId());
                    }
                    return "redirect:"+requestUrl;
                }
            }
            // 获取记录进行判断
        } else if(phoneLogin.equals(type)){
            String ph = request.getParameter("phone");
            String code = request.getParameter("code");
            // 获取之前的数据，非空判断
            if(!(StringUtils.isEmpty(ph) || StringUtils.isEmpty(code))){
                if(ph.equals(beforePhone) && code.equals(beforeCode)){
                    User user = usi.checkUser(ph);
                    // 判断是否已被封禁
                    if(user.getIsDelete() == 1){
                        return "redirect:/login.htm?error=c2&ttr="+encodingUrl;
                    }
                    // 登录成功，将用户的信息存进session前往首页
                    HttpSession userSession = request.getSession();
                    userSession.setMaxInactiveInterval(60*30);
                    userSession.setAttribute("user",user);
                    // 获取购物车商品，存进session
                    List<Product> productList = cartService.findCartProduct(user.getUserId());
                    if(productList.size()>5){
                        userSession.setAttribute("carts", productList.subList(0, 5));
                    } else {
                        userSession.setAttribute("carts", productList);
                    }
                    String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                    UserOnline userOnline = usi.findDayUserOnline(new UserOnline(0,user.getUserId(),0,nowDate, nowDate));
                    if(null == userOnline) {
                        usi.addUserOnlineCount(user.getUserId());
                    }
                    return "redirect:"+requestUrl;
                }
            }

        }
        return "redirect:/login.htm?error=c1&ttr="+encodingUrl;
    }

    /**
     * 登录-发送验证码
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping("/send_code")
    public String sendCode(@RequestParam("phone") String phone){
        // 发送验证码
        sendOutPhone(phone);
        return "yes";
    }

    /**
     * 找回密码 - 判断登录名是否存在
     * @param request
     * @return
     */
    @RequestMapping(value = "/check_name", method = RequestMethod.POST)
    public String checkLoginName(HttpServletRequest request){
        HttpSession session = request.getSession();
        // 获取jsp页面传过来的登录名，登录名可以是邮箱，手机，会员名
        String loginName = request.getParameter("user");
        User user = usi.checkUser(loginName);
        if(null == user){
            session.setMaxInactiveInterval(5);
            session.setAttribute("msg", "该账户不存在，请重新输入");
            return "redirect:/user/find_password.htm";
        }
        // 将用户手机存进session中，有效期，3分钟
        session.setMaxInactiveInterval(180);
        session.setAttribute("fpUser", user);
        return "redirect:/user/reset_password.htm";
    }

    /**
     * 找回密码-发送验证码
     * @param phone
     * @return
     */
    @RequestMapping("/rp_send")
    public String rpSendCode(@RequestParam("phone") String phone){
        sendOutPhone(phone);
        return "redirect:/user/phone_check.htm";
    }

    /**
     * 通过手机找回密码
     * @param request
     * @return
     */
    @RequestMapping("/phone_fp")
    public String PhoneToFillPassword(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(10);
        String phone = request.getParameter("phone");
        String code = request.getParameter("code");

        if(beforeCode.equals("expired") || beforePhone.equals("expired")){
            session.setAttribute("msg", "效验码已失效");
            return "redirect:/user/phone_check.htm";
        }
        // 将上一次的手机和验证码与之进行比较
        if(!(beforePhone.equals(phone) && beforeCode.equals(code))){
            session.setAttribute("msg", "效验码错误");
            return "redirect:/user/phone_check.htm";
        }
        session.setMaxInactiveInterval(180);
        session.setAttribute("type", "phone");
        return "redirect:/user/fill_password.htm";
    }

    /**
     * 忘记密码 - 发送邮件
     * @param request
     * @return
     */
    @RequestMapping("/ps_email")
    @SneakyThrows
    public String sendEmail(HttpServletRequest request){
        String email = request.getParameter("email");
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(180);
        session.setAttribute("type", "email");
        // 调用发送邮件方法
        MailUtil.sendMail(email, null, 2, ""+TotoroUtils.getServerAddress()+"/user/fill_password.htm");
        return "redirect:/user/email_check.htm";
    }

    /**
     * 忘记密码 - 修改密码
     * @param value
     * @param password
     * @return
     */
    @RequestMapping("/update_password")
    public String updatePassword(@RequestParam("value") String value, @RequestParam("password") String password){
        // 将密码进行加密，获取密码盐
        String salt = ToolSecurityPwd.generateSalt();
        // 获取加密后的密文
        String newPassWord = ToolSecurityPwd.getEncryptedPassword(password, salt);

        usi.updatePassword(value, newPassWord, salt);
        return "redirect:/login.htm";
    }


    /**
     * 发送验证码方法
     * @param phone
     */
    public void sendOutPhone(String phone){
        // 发送验证码，将手机和验证码存进session中
        // 获取效验码
        String code = TotoroUtils.getRandomNickname(6);
        // 调用发送验证码方法
//        String msg = PhoneUtil.sendPhoneCode(phone, code);
        System.out.println("此次验证码："+code);
        beforePhone = phone;
        beforeCode = code;
        // 定时器 3分钟后 自动过期
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                beforeCode = "expired";
                beforeCode = "expired";
                timer.cancel();
            }
        },300*1000);
    }

}
